package com.toman.ui.msg;


import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.githang.statusbar.StatusBarCompat;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.squareup.picasso.Picasso;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.MessageDataBean;
import com.toman.MyApplication;
import com.toman.R;
import com.toman.Util.IntentUtils;
import com.toman.Util.NetworkUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.StringUtils;
import com.toman.Util.TimeUtil;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.ui.work.device.CompleteEquipmentActivity;
import com.toman.ui.work.device.DeviceRepairActivity;
import com.toman.ui.work.device.PreMaintenanceActivity;
import com.toman.ui.work.device.TallyActivity;
import com.toman.ui.work.management.ProblemFeedbackActivity;
import com.toman.ui.work.workshop.DispatchingActivity;
import com.toman.ui.work.workshop.GetActivity;
import com.toman.ui.work.workshop.PlanActivity;
import com.toman.ui.work.workshop.SubmitActivity;
import com.toman.widget.ClearEditText;
import com.toman.widget.RecycleViewDivider;
import com.umeng.analytics.MobclickAgent;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class MsgFragment extends Fragment {
    View rootView;
    Unbinder unbinder;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rv_msg)
    RecyclerView rvMsg;
    CommonAdapter<MessageDataBean> adapter;
    @BindView(R.id.bga_refresh)
    BGARefreshLayout bgaRefresh;
    @BindView(R.id.et_search)
    ClearEditText etSearch;
    @BindView(R.id.mMangeNodata)
    TextView mMangeNodata;
    private List<MessageDataBean> listData = new ArrayList<>();

    public MsgFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rootView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_msg,
                null);
        ButterKnife.bind(this, rootView);
        initView();
//        initList();

//        test();
    }

    private void initList() {
        String items[] = new String[]{"接入产线数", "当日总产量", "当月总产量"};
        String times[] = new String[]{"2017-03-01 16:32:34", "2018-08-08 16:32:34", "2018-08-07 16:32:34"};
        String nums[] = new String[]{"1", "10", "111"};

        for (int i = 0; i < items.length; i++) {
            MessageDataBean bean = new MessageDataBean();
            bean.setName(items[i]);
            bean.setCount(nums[i]);
            bean.setMessageTime(times[i]);
            listData.add(bean);
        }
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        rvMsg.setLayoutManager(manager);
        adapter.notifyDataSetChanged();


    }

    private void initView() {

        adapter = new CommonAdapter<MessageDataBean>(getActivity(), R.layout.item_msg, listData) {
            @Override
            protected void convert(ViewHolder holder, MessageDataBean item, final int position) {
                holder.setText(R.id.tv_name, item.getName());

                holder.setText(R.id.tv_content,StringUtils.stringFilter(StringUtils.ToDBC(item.getMessageContent())) );


                holder.setText(R.id.tv_count, item.getCount());
                holder.setText(R.id.tv_time, TimeUtil.getFormatTime(TimeUtil.convert2long(item.getMessageTime())));
                if (position + 1 == listData.size()) {
                    holder.getView(R.id.line).setVisibility(View.GONE);
                }
                if (StringUtils.isNotEmpty(item.getUrl()) ) {
                    Picasso.with(getActivity()).load(item.getUrl()).into((ImageView) holder.getView(R.id.iv_icon));
                }
            }
        };
        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                List<MessageDataBean> beanlist = adapter.getDatas();
                MessageDataBean bean = beanlist.get(position);
                ToastUtil.print(bean.getType() + "：" + bean.getOperateType());
                Bundle bundle=new Bundle();
                bundle.putString("type",bean.getType());
                bundle.putString("title",bean.getName());
                IntentUtils.startActivity(getActivity(),MsgActivity.class,bundle);
//                dealMsg(bean);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        rvMsg.setAdapter(adapter);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        rvMsg.setLayoutManager(manager);

        bgaRefresh.setRefreshViewHolder(new BGANormalRefreshViewHolder(MyApplication.getInstance(), false));

        bgaRefresh.setDelegate(new BGARefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
                if (NetworkUtils.checkNetState(getActivity())) {
                    // 如果网络可用，则加载网络数据
                    get();

                } else {
                    // 网络不可用，结束下拉刷新
                    bgaRefresh.endRefreshing();
                }
            }

            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
                return false;
            }
        });
//        PlusItemSlideCallback callback = new PlusItemSlideCallback(WItemTouchHelperPlus.SLIDE_ITEM_TYPE_ITEMVIEW,getContext());
//        WItemTouchHelperPlus extension = new WItemTouchHelperPlus(callback);
//        extension.attachToRecyclerView(rvMsg);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        // Inflate the layout for this fragment
        Log.i("test", "AFragment-->onCreateView");
        ViewGroup perentView = (ViewGroup) rootView.getParent();
        if (perentView != null) {
            perentView.removeAllViewsInLayout();
        }
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        StatusBarCompat.setStatusBarColor(getActivity(), getResources().getColor(R.color.white), true);
        MobclickAgent.onPageStart("消息页"); //统计页面，"MainScreen"为页面名称，可自定义
        try {
            get();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("消息页");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public void dealMsg(MessageDataBean bean) {
        switch (bean.getType()) {
            case "1":
                Bundle bundle = new Bundle();
                bundle.putString("status", bean.getOperateType());
                IntentUtils.startActivity(getActivity(), TallyActivity.class, bundle);
                break;

            case "2":
                bundle = new Bundle();
                bundle.putString("status", bean.getOperateType());
                IntentUtils.startActivity(getActivity(), CompleteEquipmentActivity.class, bundle);
                break;
            case "3":
                bundle = new Bundle();
                bundle.putString("status", bean.getOperateType());
                IntentUtils.startActivity(getActivity(), PreMaintenanceActivity.class, bundle);
                break;
            case "4":
                bundle = new Bundle();
                bundle.putString("status", bean.getOperateType());
                IntentUtils.startActivity(getActivity(), DeviceRepairActivity.class, bundle);
                break;

            case "6":
                bundle = new Bundle();
                bundle.putString("status", bean.getOperateType());
                IntentUtils.startActivity(getActivity(), PlanActivity.class, bundle);
                break;
            case "7":

                bundle = new Bundle();
                bundle.putString("status", bean.getOperateType());
                IntentUtils.startActivity(getActivity(), DispatchingActivity.class, bundle);
                break;
            case "8":
                bundle = new Bundle();
                bundle.putString("status", bean.getOperateType());
                IntentUtils.startActivity(getActivity(), GetActivity.class, bundle);
                break;
            case "9":
                bundle = new Bundle();
                bundle.putString("status", bean.getOperateType());
                IntentUtils.startActivity(getActivity(), SubmitActivity.class, bundle);
                break;

            case "12":
                bundle = new Bundle();
                bundle.putString("status", bean.getOperateType());
                IntentUtils.startActivity(getActivity(), ProblemFeedbackActivity.class, bundle);
                break;
        }

    }

    public void get() {
        String token = (String) SPUtils.get(getActivity(), "token", "");
        OkHttpUtils
                .post(NewBaseUrl.getAllNotifyMessage)
                .headers("token", token)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "消息详情: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");

                        ViewUtil.lagout(code, getActivity());
                        if (code == 0) {
                            listData.clear();
                            List<MessageDataBean> jsonArray = new ArrayList<MessageDataBean>(JSONArray.parseArray(jsonObj.getString("data"), MessageDataBean.class));
                            listData.addAll(jsonArray);
                            adapter.notifyDataSetChanged();

                            try {
                                if (listData.size()<=0){
                                    mMangeNodata.setVisibility(View.VISIBLE);
                                }
                                else {mMangeNodata.setVisibility(View.GONE);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }

                            else {
                            ToastUtil.makeText(getActivity(), jsonObj.getString("msg"));

                        }
                        if (bgaRefresh!=null){
                            bgaRefresh.endRefreshing();
                        }
                    }
                });
    }

}
